import React, { Component } from 'react';
import {
  View,
  Text,
  Image,
  ScrollView,
  TouchableOpacity,
  WebView,
} from 'react-native';

import { getRequest } from '../../tools/network';



export default class News extends Component {
  static navigationOptions = {
    header: null,
    // title: '知乎首页',
  };

  state = {
    newsJson: '',
  }

  componentDidMount() {
    var url = 'https://zhihu-daily.leanapp.cn/api/v1/contents/' + this.props.navigation.state.params.id;

    getRequest(url, function (json) {
      this.setState({
        newsJson: json,
      })
    }.bind(this));

  }

  render() {
    var navigation = this.props.navigation;

    var newsBodyHTML = '';
    var css = '';
    // var img = 'https://facebook.github.io/react/img/logo_og.png';
    var img = ' ';
    var title = '';
    var image_source = '';

    if (this.state.newsJson) {
      newsBodyHTML = this.state.newsJson.CONTENTS.body;
      css = this.state.newsJson.CONTENTS.css[0];
      img = this.state.newsJson.CONTENTS.image;
      title = this.state.newsJson.CONTENTS.title;
      image_source = this.state.newsJson.CONTENTS.image_source;

      // newsBodyHTML += css += `<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no">`;

      newsBodyHTML =
      `
        <meta name='viewport' content='width=device-width, initial-scale=1, shrink-to-fit=no'>
        <link rel='stylesheet' href='${css}'>
        ${newsBodyHTML}
      `;
    }

    return (
      <ScrollView style={{ flex: 1 }}>
        <WebContainer
          html={newsBodyHTML} />


        <View style={styleSheet.header}>
          <Image source={{ uri: img }}
            style={styleSheet.logo} />

          <Text style={styleSheet.title}>
            {title}
          </Text>

          <Text style={styleSheet.image_source}>
            图片：{image_source}
          </Text>
        </View>
      </ScrollView>
    );
  }
};


var styleSheet = {
  header: {
    width: '100%',
    position: 'absolute',
    height: 200,
  },

  logo: {
    width: '100%',
    // position: 'absolute',
    height: '100%',
    // height: 140,
  },

  title: {
    bottom: 70,
    color: 'white',
    width: '90%',
    left: '5%',
    lineHeight: 20,
    fontSize: 16,
    backgroundColor: 'transparent',
  },

  image_source: {
    position: 'absolute',
    bottom: 10,
    right: 5,
    color: 'white',
    fontSize: 10,
    backgroundColor: 'transparent',
  },

  webView: {
    position: 'absolute',
    top: 0,
    right: 0,
    left: 0,
    bottom: 0,
    // height: 1000,
    // flex: 1,
    backgroundColor: 'red',
  },
}




const script = `<script>
      function _autoHeight(){
        window.location.hash = Date.now();
        document.title = document.documentElement.offsetHeight;
        document.body.style.height = document.documentElement.offsetHeight;
      }
      window.addEventListener('load', _autoHeight)
    </script>`;

let safeHtml = function (html) {
  if (!html) {
    return ''
  }
  return `
  <!DOCTYPE html>
  <html>
    <head>
      <meta charset="utf-8">
      <title></title>
      <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no">
    </head>
    <body>
      ${html}
      ${script}
    </body>
  </html>
  `
}

class WebContainer extends Component {
  constructor(props) {
    super();
    this.state = {
      height: Number(props.height) || 0
    };
  }

  onNavigationStateChange(navState) {
    let h = Number(navState.title) || 0
    if (h) {
      this.setState({
        height: h
      });
    }
  }
  shouldComponentUpdate(nextProps, nextState) {
    if (this.props.html == nextProps.html
      && this.state.height == nextState.height) {
      return false
    }
    return true
  }
  render() {
    let {
      html,
      style,
      scrollEnabled,
      ...props
    } = this.props;
    // console.log(this.state.height, html)
    let page = safeHtml(html || '');
    if (!page) {
      return (<View />)
    }
    return (
      <WebView
        {...props}
        style={[style, { height: Number(this.state.height) }]}
        scrollEnabled={false}
        source={{ html: page, baseUrl: '', title: '' }}
        ref={(c) => { this.webview = c }}
        automaticallyAdjustContentInsets={true}
        javaScriptEnabled={true}
        domStorageEnabled={true}
        decelerationRate="normal"
        startInLoadingState={false}
        scalesPageToFit={true}
        scrollEnabled={false}
        onNavigationStateChange={this.onNavigationStateChange.bind(this)} />
    );
  }
}
